<template>
	<div>
		<h1 v-for="item in messages">{{ item }}</h1>
	</div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import tool from "@/utils/tool";
import sysConfig from "@/config";
import {convertUrl} from "@/utils/apiAdaptive";
import {EventSourcePolyfill} from "event-source-polyfill";

const messages = ref([]);

onMounted(() => {
	createSseConnect()
})

// 创建sse连接
const createSseConnect = () => {
	if (window.EventSource) {
		let clientId = tool.data.get('CLIENTID') ? tool.data.get('CLIENTID') : generateRandomNumber();
		console.log('clientId : ', clientId)
		// let url = sysConfig.API_URL + convertUrl('/bizapp/sseDistributedConnect?clientId=123') + clientId
		let url = sysConfig.API_URL + convertUrl('/bizapp/sseDistributedConnect?clientId=123');
		console.log('tool : ', tool.data.get('TOKEN'))
		// heartbeatTimeout:心跳超时监测 30s
		let source = new EventSourcePolyfill(url, {
			headers: {Token: tool.data.get('TOKEN')},
			heartbeatTimeout: 300000
		})
		console.log('source : ', source)
		// 监听打开事件
		source.addEventListener('open', (e) => {
			console.log('sse连接成功')
			if (tool.data.get('CLIENTID') === null) {
				tool.data.set('CLIENTID', clientId)
			}
		})
		// 监听消息事件
		source.addEventListener('message', (e) => {
			console.log("监听到的消息 ", e)
			const result = JSON.parse(e.data)
			messages.value.push(result)
		})
		// 监听错误事件
		source.addEventListener('error', (e) => {
			console.error('发生错误，消息实时获取已断开与服务器的连接')
			source.close()
		})
	} else {
		console.error('该浏览器不支持消息功能')
	}
}

const generateRandomNumber = () => {
	// 生成一个10位的随机数字
	return Math.floor(Math.random() * 9000000000) + 1000000000;
}

</script>

